import { defineStore } from 'pinia'
import { 
  SUPPORTED_LOCALES, 
  DEFAULT_LOCALE, 
  getBrowserLanguage, 
  getStoredLanguage, 
  setStoredLanguage, 
  clearStoredLanguage,
  isValidLocale,
  getLocaleInfo 
} from '../../i18n/i18n'

export const useLanguageStore = defineStore('language', {
  state: () => ({
    // 当前语言代码
    currentLocale: DEFAULT_LOCALE,
    // 是否已初始化
    isInitialized: false,
    // 浏览器检测到的语言
    browserLanguage: '',
    // 存储的语言偏好
    storedLanguage: null as string | null
  }),

  getters: {
    // 获取当前语言信息
    currentLocaleInfo: (state) => getLocaleInfo(state.currentLocale),
    
    // 获取所有支持的语言
    availableLocales: () => SUPPORTED_LOCALES,
    
    // 检查是否有存储的语言偏好
    hasStoredPreference: (state) => !!state.storedLanguage,
    
    // 获取语言显示名称
    currentLanguageName: (state) => getLocaleInfo(state.currentLocale)?.name || state.currentLocale,
    
    // 检查是否为默认语言
    isDefaultLanguage: (state) => state.currentLocale === DEFAULT_LOCALE
  },

  actions: {
    /**
     * 初始化语言系统
     * @param i18nInstance i18n 实例
     * @param forceLocale 强制设置的语言（可选）
     */
    async initializeLanguage(i18nInstance: any, forceLocale?: string) {
      if (this.isInitialized && !forceLocale) return

      try {
        // 获取浏览器语言
        this.browserLanguage = getBrowserLanguage()
        
        // 获取存储的语言偏好
        this.storedLanguage = getStoredLanguage()
        
        // 确定目标语言
        const targetLocale = forceLocale || this.getInitialLanguage()
        
        if (isValidLocale(targetLocale)) {
          await this.switchLanguage(i18nInstance, targetLocale, !forceLocale)
        } else {
          console.warn(`无效的语言代码: ${targetLocale}，使用默认语言`)
          await this.switchLanguage(i18nInstance, DEFAULT_LOCALE, false)
        }
        
        this.isInitialized = true
        console.log('语言系统初始化完成:', {
          current: this.currentLocale,
          browser: this.browserLanguage,
          stored: this.storedLanguage
        })
      } catch (error) {
        console.error('语言系统初始化失败:', error)
        this.currentLocale = DEFAULT_LOCALE
        this.isInitialized = true
      }
    },

    /**
     * 切换语言
     * @param i18nInstance i18n 实例
     * @param newLocale 新语言代码
     * @param saveToStorage 是否保存到本地存储
     */
    async switchLanguage(i18nInstance: any, newLocale: string, saveToStorage: boolean = true) {
      if (!isValidLocale(newLocale)) {
        console.warn(`不支持的语言代码: ${newLocale}`)
        return false
      }

      try {
        // 更新 i18n 实例
        i18nInstance.locale.value = newLocale
        
        // 更新状态
        this.currentLocale = newLocale
        
        // 保存到本地存储
        if (saveToStorage) {
          setStoredLanguage(newLocale)
          this.storedLanguage = newLocale
        }
        
        console.log('语言切换成功:', {
          to: newLocale,
          saved: saveToStorage
        })
        
        return true
      } catch (error) {
        console.error('语言切换失败:', error)
        return false
      }
    },

    /**
     * 获取初始语言（智能选择）
     */
    getInitialLanguage(): string {
      // 1. 检查用户存储的偏好
      if (this.storedLanguage && isValidLocale(this.storedLanguage)) {
        return this.storedLanguage
      }
      
      // 2. 检查浏览器语言
      if (this.browserLanguage && this.browserLanguage !== DEFAULT_LOCALE) {
        return this.browserLanguage
      }
      
      // 3. 返回默认语言
      return DEFAULT_LOCALE
    },

    /**
     * 清除语言缓存
     * @param i18nInstance i18n 实例
     */
    async clearLanguageCache(i18nInstance: any) {
      try {
        // 清除本地存储
        clearStoredLanguage()
        this.storedLanguage = null
        
        // 恢复到浏览器语言
        const browserLanguage = this.getInitialLanguage()
        await this.switchLanguage(i18nInstance, browserLanguage, false)
        
        console.log('语言缓存已清除，恢复到浏览器语言:', browserLanguage)
        return true
      } catch (error) {
        console.error('清除语言缓存失败:', error)
        return false
      }
    },

    /**
     * 检查语言是否支持
     * @param locale 语言代码
     */
    isLocaleSupported(locale: string): boolean {
      return isValidLocale(locale)
    },

    /**
     * 获取语言信息
     * @param locale 语言代码
     */
    getLocaleInfo(locale: string) {
      return getLocaleInfo(locale)
    }
  }
})
